package com.zprmb.udzt.util;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import android.app.Activity;
import android.util.Log;

import com.zprmb.udzt.view.LoadingDialog;
import com.zprmb.udzt.vo.AuthFailureError;
import com.zprmb.udzt.vo.DefaultRetryPolicy;
import com.zprmb.udzt.vo.RequestQueue;
import com.zprmb.udzt.vo.Response;
import com.zprmb.udzt.vo.VolleyError;
import com.zprmb.udzt.vo.toolbox.JsonObjectRequest;
import com.zprmb.udzt.vo.toolbox.Volley;

public abstract class VolleryUtil2 {

	private LoadingDialog ld;
	private RequestQueue mQueue;
	private Map<String, String> headers = new HashMap<String, String>();
	private boolean isShow;
	private int requestMethod = 1;
   
	public void setRequestMethod(int requestMethod) {
		this.requestMethod = requestMethod;
	}
   
	public boolean isShow() {
		return isShow;
	}
	

	public void setShow(boolean isShow) {
		this.isShow = isShow;
	}

	public void setHeaders(String key, String values) {
		headers.put(key, values);
	}

	/**
	 * 网络访问错误
	 */
	public abstract void onError();

	/**
	 * loading框
	 */
	// public abstract void onLoading();

	/**
	 * 更新界面
	 */
	public abstract void onUpDate(JSONObject jsonObject);

	private void doInBackground(final Activity context, String url,
			String params) {
		StringBuffer sb = new StringBuffer();
		if (ld == null) {
			ld = new LoadingDialog(context);
		}
		if (params.equals("")) {
			sb.append(url);
		} else {
			sb.append(url);
			sb.append(params);
		}
		if (isShow) {
			try {
				ld.show();
				
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		if (mQueue == null) {
			mQueue = Volley.newRequestQueue(context);
		}
		// System.out.println("vollery====" + sb.toString());
		// get 0 post 1
		JsonObjectRequest json = new JsonObjectRequest(requestMethod,
				sb.toString(), null, new Response.Listener<JSONObject>() {
					public void onResponse(JSONObject response) {
						onUpDate(response);
						ld.close();
						
					}
				}, new Response.ErrorListener() {
					public void onErrorResponse(VolleyError error) {
						onError();
						Log.e("错误", error.toString());
						ld.close();
					}
				}) { 
			public Map<String, String> getHeaders() throws AuthFailureError {
				headers.put("UserAgent", "rmbbox_android");
				return headers;
			}
		};
		mQueue.add(json);
		json.setRetryPolicy(new DefaultRetryPolicy(3000,DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));   
	}

	public void execute(Activity context, String url, String params) {
		ld = null;
		doInBackground(context, url, params);
	}
}
